<?php

include 'parseInput.php';

function get_answer_from_db($tags_from_user) {
	
	$dbhost = "localhost";
	$dbuser = "root";
	$dbpass = "";
	$dbname = "fei_hackathon";

	$tags_array = explode(',', $tags_from_user);
	$greatest_tag_value = 0;
	$id_to_return = "";
	$final_result ="";
	
	
	$con_db=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die ('Error connecting with the server');
	
	// Check connection
	if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}



	

	//Build SELECT Query
	$select_query = "SELECT * FROM answer WHERE";
	
	foreach ($tags_array as $value) {
		$select_query = $select_query." Tags Like '%$value%' AND";
	}
	
	//Remove extra " AND"
	$select_query = substr($select_query,0,strlen($select_query) - 4);	
	
	$result = mysqli_query($con_db,$select_query);
	
		//check each match for the accuracy of the match
	while($row = mysqli_fetch_array($result)) {
			$no_of_tags = $row['No_of_Tags'];
			
			if($no_of_tags > $greatest_tag_value) {
				$greatest_tag_value = $no_of_tags;
				$id_to_return = $row['Answer_ID'];
			}
	}
	
	$result = mysqli_query($con_db,"SELECT Answer FROM answer WHERE Answer_ID = $id_to_return");
	$final_result = mysqli_fetch_array($result);
	$final_result = $final_result[0];
	
	
	mysqli_close($con_db);
	
	return $final_result;
}

echo get_answer_from_db(parse_input("Who Started Fac is are"));
?>